package lv.accenture.ex06;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class ProcessingMain {
	
	public static void writeJSON(String fileName, List<Bookmark> bookmarks) throws IOException {
		  FileOutputStream fis = new FileOutputStream(fileName);
		  OutputStreamWriter osw = new OutputStreamWriter(fis, "UTF-8");
		  BufferedWriter bw = new BufferedWriter(osw);
			    
		  bw.write("{\"items\" : [\n"); // write preamble of JSON file
		  StringBuffer s = new StringBuffer();
		  int i = 0;
		  for (Bookmark b: bookmarks) {
		    //bw.write(b.toString()+","); // output each bookmark
			  s.append(b.toString());
			  s.append(",\n");
			  ++i;
		  }
		  System.out.println(i);
		  
		  bw.write(s.toString().substring(0, s.length()-2));
		  bw.write("]}"); // write closing part of JSON
		  bw.close();
		  osw.close();
		  fis.close();
		}
	
	public static void main(String[] args) throws IOException {
		IResourceList rList = new FSResourceList("src/main/resources/retiman");
		String[] resources = rList.getAllResources();
		System.out.println("total # of tags is " + resources.length);

		RegexExtractor extractor = new RegexExtractor();
		
		List<Bookmark> bm = new ArrayList<Bookmark>();
		for (int i = 0; i < resources.length; i++) {
			bm.addAll(extractor.extractBookmarks(resources[i]));
		}
		writeJSON("bookmarks.js", bm);
		
		System.out.println("END");
	}
}
